package com.elong.android.specialhouse.ui;

import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import android.widget.ViewSwitcher.ViewFactory;


public class PagedGallery extends ViewSwitcher implements ViewFactory, OnGestureListener {
    public final static String TAG = "PagedGallery";

    // private ArrayList<HashMap<String,Object>> m_data;
    // private String m_imageKey;
    private int m_selectedIndex;
    private GestureDetector m_gestureDetector;
    private AdapterView.OnItemClickListener m_onItemClickListener;
    private AdapterView.OnItemSelectedListener m_onItemSelectedListener;
    protected BaseAdapter m_adapter;
    protected GalleryDataSetObserver m_dataObeserver;
    private ImageView imageView;
    private static final LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.FILL_PARENT);

    // animations.
    public final static int DEFAULT_ANIMATIONDDURATION = 500;
    private TranslateAnimation m_animSlideinFromLeft;
    private TranslateAnimation m_animSlideoutFromLeft;
    private TranslateAnimation m_animSlideinFromRight;
    private TranslateAnimation m_animSlideoutFromRight;
    private int m_animationDuration = DEFAULT_ANIMATIONDDURATION;

    public PagedGallery(Context context, AttributeSet attrs) {
        super(context, attrs);
        setFactory(this);
        m_gestureDetector = new GestureDetector(context, this);
        m_gestureDetector.setIsLongpressEnabled(true);
        m_dataObeserver = new GalleryDataSetObserver(this);
        // setOnTouchListener(this);

        // initAnimations.
        AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator();
        m_animSlideinFromLeft = new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        m_animSlideinFromLeft.setInterpolator(interpolator);
        m_animSlideinFromLeft.setDuration(m_animationDuration);

        m_animSlideoutFromLeft = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        m_animSlideoutFromLeft.setInterpolator(interpolator);
        m_animSlideoutFromLeft.setDuration(m_animationDuration);

        m_animSlideinFromRight = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        m_animSlideinFromRight.setInterpolator(interpolator);
        m_animSlideinFromRight.setDuration(m_animationDuration);

        m_animSlideoutFromRight = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                1.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        m_animSlideoutFromRight.setInterpolator(interpolator);
        m_animSlideoutFromRight.setDuration(m_animationDuration);
    }

    public void setAnimationDuration(int duration) {
        m_animationDuration = duration;
        m_animSlideinFromLeft.setDuration(duration);
        m_animSlideoutFromLeft.setDuration(duration);
        m_animSlideinFromRight.setDuration(duration);
        m_animSlideoutFromRight.setDuration(duration);
    }

	/*
     * public void setData(ArrayList<HashMap<String,Object>> data,String
	 * imageKey) { m_data = data; m_imageKey = imageKey; notifyDatasetChanged();
	 * }
	 */

    public BaseAdapter getAdapter() {
        return m_adapter;
    }

    public void setAdapter(BaseAdapter adapter) {
        if (m_adapter != null) {
            m_adapter.unregisterDataSetObserver(m_dataObeserver);
        }
        m_adapter = adapter;
        m_adapter.registerDataSetObserver(m_dataObeserver);
        notifyDatasetChanged();
        // reset();
    }

    private void notifyDatasetChanged() {
        setSelection(this.getSelectedItemPosition());
    }

    public View makeView() {
        imageView = new ImageView(this.getContext());
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        // i.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setLayoutParams(layout);
        return imageView;
    }

    public void setSelection(int position) {
        if (m_adapter != null) {
			/*
			 * Bitmap img = (Bitmap) m_data.get(position).get(m_imageKey);
			 * if(img != null) { setImageDrawable(new BitmapDrawable(img)); }
			 */
            boolean scroll2Right = position > m_selectedIndex;
            boolean scroll2Left = position < m_selectedIndex;
            if (scroll2Right) {
                setInAnimation(m_animSlideinFromRight);
                setOutAnimation(m_animSlideoutFromLeft);
            } else if (scroll2Left) {
                setInAnimation(m_animSlideinFromLeft);
                setOutAnimation(m_animSlideoutFromRight);
            }
            View v = null;
            try {
                v = m_adapter.getView(position, null, this);
            } catch (Exception e) {
//                Debug.u(TAG, e.toString());
            }
            if (v != null) {
                if (getChildCount() >= 2) {
                    removeViewAt(0);
                }
                addView(v);
                showNext();
            }
            boolean triggerSelectionEvent = m_selectedIndex != position;

            m_selectedIndex = position;
            if (triggerSelectionEvent) {
                if (m_onItemSelectedListener != null) {
                    m_onItemSelectedListener.onItemSelected(null, this, m_selectedIndex, 0);
                }
            }
        }
    }

    public int getSelectedItemPosition() {
        return m_selectedIndex;
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener listener) {
        m_onItemClickListener = listener;
    }

    public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener) {
        m_onItemSelectedListener = listener;
    }

    public boolean onTouchEvent(MotionEvent event) {
        return m_gestureDetector.onTouchEvent(event);
    }

    public boolean onDown(MotionEvent e) {
        return true;
    }

    public final static int MIN_FLING_DISTANCE = 90;

    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        // Log.v(TAG, "onFling...");
        if (e1 == null || e2 == null) {
            return false;
        }
        float x1 = e1.getX();
        float x2 = e2.getX();
        if (x1 - x2 > MIN_FLING_DISTANCE) {
            // fling to left.
            if (getAdapter() != null && m_selectedIndex < getAdapter().getCount() - 1) {
                setSelection(m_selectedIndex + 1);
                return true;
            }
        } else if (x2 - x1 > MIN_FLING_DISTANCE) {
            // fling to right.
            if (getAdapter() != null && m_selectedIndex > 0) {
                setSelection(m_selectedIndex - 1);
                return true;
            }
        }
        return true;
    }

    public void onLongPress(MotionEvent e) {

    }

    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return true;
    }

    public void onShowPress(MotionEvent e) {

    }

    public boolean onSingleTapUp(MotionEvent e) {
        if (getAdapter() != null && m_onItemClickListener != null) {
            m_onItemClickListener.onItemClick(null, this, m_selectedIndex, 0);
        }
        return true;
    }

    private class GalleryDataSetObserver extends DataSetObserver {
        private PagedGallery m_gallery;

        public GalleryDataSetObserver(PagedGallery gallery) {
            m_gallery = gallery;
        }

        public void onChanged() {
            // m_list.reset();
            m_gallery.notifyDatasetChanged();
        }
    }
}
